package com.txd.mofa.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bytedance.sdk.open.aweme.TikTokConstants;
import com.bytedance.sdk.open.aweme.TikTokOpenApiFactory;
import com.bytedance.sdk.open.aweme.api.TiktokOpenApi;
import com.bytedance.sdk.open.aweme.base.TikTokImageObject;
import com.bytedance.sdk.open.aweme.base.TikTokMediaContent;
import com.bytedance.sdk.open.aweme.base.TikTokVideoObject;
import com.bytedance.sdk.open.aweme.share.Share;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kongzue.baseframework.util.Preferences;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.OnDownloadListener;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com.txd.mofa.R;
import com.txd.mofa.adapter.FenxiangAdapter;
import com.txd.mofa.bean.ShaixuanBean;
import com.txd.mofa.login.BangdingAty;
import com.txd.mofa.net.NetUtils;
import com.txd.mofa.share.ShareBeBackListener;
import com.txd.mofa.share.ShareForApp;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import static com.txd.mofa.http.HttpUtils.woindex;

/**
 * Created by bin on 2018/12/21.
 */

public class FenxiangDialog extends Dialog implements View.OnClickListener, ShareBeBackListener, PlatformActionListener {

    private String type;
    private int pos;
    private Map<String, String> stringStringMap;
    private SignListener signListener;
    private Context context;
    private TextView tv_quxiao, tv;
    private boolean flag;
    private String type_id;
    private String fenlei;
    private Activity activity;

    private String token;
    private FenxiangAdapter fenxiangAdapter1;
    private FenxiangAdapter fenxiangAdapter;

    public FenxiangDialog(@NonNull Context context, String type_id, String fenlei, String type, boolean is_myself_post, @NonNull SignListener signListener) {
        super(context, R.style.share_style);
        this.type = type;
        this.signListener = signListener;
        flag = is_myself_post;
        this.context = context;
        this.type_id = type_id;
        this.fenlei = fenlei;
        token = Preferences.getInstance().getString(context, "heima", "token");
    }

    public FenxiangDialog(@NonNull Activity context, int pos, Map<String, String> stringStringMap, @NonNull SignListener signListener) {
        super(context, R.style.share_style);
        this.pos = pos;
        this.context = context;
        this.stringStringMap = stringStringMap;
        this.signListener = signListener;
        activity = context;


        HttpRequest.POST(context, woindex, new Parameter().add("token",Preferences.getInstance().getString(context, "mofa", "token")), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                        Preferences.getInstance().set(context,"shouji","shouji",data.get("account"));

                    }


                }else {

                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fenxiang_dialog);

        Window window = this.getWindow();

        //解决 状态栏变色的bug
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(Color.TRANSPARENT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                try {
                    Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                    Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                    field.setAccessible(true);
                    field.setInt(getWindow().getDecorView(), Color.TRANSPARENT);  //去掉高版本蒙层改为透明
                } catch (Exception e) {
                }
            }
        }

        findViewById(R.id.view).setOnClickListener(this);
        findViewById(R.id.tv_quxiao).setOnClickListener(this);
        RecyclerView recy = findViewById(R.id.recy);
        RecyclerView recy1 = findViewById(R.id.recy1);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recy.setLayoutManager(linearLayoutManager);

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(context);
        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        recy1.setLayoutManager(linearLayoutManager1);

        fenxiangAdapter = new FenxiangAdapter(R.layout.item_fenxiang);
        recy.setAdapter(fenxiangAdapter);

        fenxiangAdapter1 = new FenxiangAdapter(R.layout.item_fenxiang);
        recy1.setAdapter(fenxiangAdapter1);


        list.add(new ShaixuanBean("微信好友", R.mipmap.wechat));
        list.add(new ShaixuanBean("朋友圈", R.mipmap.pengyouquan));
        list.add(new ShaixuanBean("QQ好友", R.mipmap.qq_fx));
        list.add(new ShaixuanBean("QQ空间", R.mipmap.qqkj_fx));
        list.add(new ShaixuanBean("微博", R.mipmap.weibo));
        list.add(new ShaixuanBean("抖音", R.mipmap.douyin_fx));
        list.add(new ShaixuanBean("复制链接", R.mipmap.fuzhilianjie));
        fenxiangAdapter.setNewData(list);

        if (pos == 0) {
            list1.add(new ShaixuanBean("举报", R.mipmap.jubao));
            list1.add(new ShaixuanBean("保存视频", R.mipmap.baocunshipin));
        } else {
            list1.add(new ShaixuanBean("举报", R.mipmap.jubao));
            list1.add(new ShaixuanBean("保存相册", R.mipmap.baocunxiangce));
        }

        fenxiangAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == 0) {
                    if (Preferences.getInstance().getString(context,"shouji","shouji").equals("")){
                        Intent intent = new Intent(context, BangdingAty.class);
                        intent.putExtra("name","绑定手机号");
                        context.startActivity(intent);
                        dismiss();
                    }else {
                        platFormName = Wechat.NAME;
                        price = context.getResources().getString(R.string.app_name);
                        platform = ShareSDK.getPlatform(platFormName);
                        if (!platform.isClientValid()) {
                            Toast.makeText(context, "请安装微信", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        toShare(platFormName);
                    }
                } else if (position == 1) {
                    if (Preferences.getInstance().getString(context,"shouji","shouji").equals("")){
                        Intent intent = new Intent(context, BangdingAty.class);
                        intent.putExtra("name","绑定手机号");
                        context.startActivity(intent);
                        dismiss();
                    }else {
                        platFormName = WechatMoments.NAME;
                        price = context.getResources().getString(R.string.app_name);
                        platform = ShareSDK.getPlatform(platFormName);
                        if (!platform.isClientValid()) {
                            Toast.makeText(context, "请安装微信", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        toShare(platFormName);
                    }
                } else if (position == 2) {
                    if (Preferences.getInstance().getString(context,"shouji","shouji").equals("")){
                        Intent intent = new Intent(context, BangdingAty.class);
                        intent.putExtra("name","绑定手机号");
                        context.startActivity(intent);
                        dismiss();
                    }else {
                        platFormName = QQ.NAME;
                        price = context.getResources().getString(R.string.app_name);
                        platform = ShareSDK.getPlatform(platFormName);
                        if (!platform.isClientValid()) {
                            Toast.makeText(context, "请安装微信", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        toShare(platFormName);
                    }
                } else if (position == 3) {
                    if (Preferences.getInstance().getString(context,"shouji","shouji").equals("")){
                        Intent intent = new Intent(context, BangdingAty.class);
                        intent.putExtra("name","绑定手机号");
                        context.startActivity(intent);
                        dismiss();
                    }else {
                        platFormName = QZone.NAME;
                        price = context.getResources().getString(R.string.app_name);
                        platform = ShareSDK.getPlatform(platFormName);
                        if (!platform.isClientValid()) {
                            Toast.makeText(context, "请安装微信", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        toShare(platFormName);
                    }
                } else if (position == 4) {
                    if (Preferences.getInstance().getString(context,"shouji","shouji").equals("")){
                        Intent intent = new Intent(context, BangdingAty.class);
                        intent.putExtra("name","绑定手机号");
                        context.startActivity(intent);
                        dismiss();
                    }else {
                        platFormName = SinaWeibo.NAME;
                        price = context.getResources().getString(R.string.app_name);
                        platform = ShareSDK.getPlatform(platFormName);
                        toShare(platFormName);
                    }
                } else if (position == 5) {

                    if (Preferences.getInstance().getString(context,"shouji","shouji").equals("")){
                        Intent intent = new Intent(context, BangdingAty.class);
                        intent.putExtra("name","绑定手机号");
                        context.startActivity(intent);
                        dismiss();
                    }else {
                        // TODO抖音

                        if (NetUtils.isNetworkAvailable(context)) {
                            if (pos == 0) {
                                xiazaiVideo(1);
                            } else {
                                xiazaiJPG(1);
                            }
                        }else {
                            Toast.makeText(context, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                        }



                    }
                } else if (position == 6) {
                    signListener.fuzhi();
                }


            }
        });

        fenxiangAdapter1.setNewData(list1);

        fenxiangAdapter1.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == 0) {
                    signListener.jubao();
                } else {
                    if (pos == 0) {
                        xiazaiVideo(0);
                    } else {
                        xiazaiJPG(0);
                    }
                }
            }
        });

    }

    private String path = "";

    public static boolean fileIsExists(String strFile){
        try {
            File file=new File(strFile);
            if (!file.exists()){
                return false;
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }



    private void xiazaiJPG(int i) {

        File baseOkHttpV3 = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "BaseOkHttpV3");

        fileIsExists(baseOkHttpV3.getAbsolutePath());

        HttpRequest.DOWNLOAD(context,
                stringStringMap.get("img"),
                new File(baseOkHttpV3, System.currentTimeMillis() + ".JPG"), new OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {

                        path = file.getAbsolutePath();

                        if (i == 1) {
                            TiktokOpenApi tiktokOpenApi = TikTokOpenApiFactory.create(context,TikTokConstants.TARGET_APP.AWEME);


                            Share.Request request = new Share.Request();
                            ArrayList<String> mUri = new ArrayList<>();
                            mUri.add(path);

                            TikTokImageObject imageObject = new TikTokImageObject();
                            imageObject.mImagePaths = mUri;
                            TikTokMediaContent mediaContent = new TikTokMediaContent();
                            mediaContent.mMediaObject = imageObject;
                            request.mMediaContent = mediaContent;

                            // 调起分享
                            tiktokOpenApi.share(request);
                        }else {
                            Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
                        }


                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(file);
                        intent.setData(uri);
                        context.sendBroadcast(intent);
                        dismiss();

                    }

                    @Override
                    public void onDownloading(int progress) {
                        Log.e("file", progress + "");
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        Toast.makeText(context, "下载失败,请重试", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void xiazaiVideo(int i) {

        File mofa = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Mofa");

        fileIsExists(mofa.getAbsolutePath());

        HttpRequest.DOWNLOAD(context,
                stringStringMap.get("video"),
                new File(mofa, System.currentTimeMillis() + ".MP4"), new OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {



                        if (i == 1) {
                            TiktokOpenApi tiktokOpenApi = TikTokOpenApiFactory.create(context,TikTokConstants.TARGET_APP.AWEME);

                            Share.Request request = new Share.Request();
                            ArrayList<String> mUri = new ArrayList<>();
                            mUri.add(file.getAbsolutePath());

                            TikTokVideoObject videoObject = new TikTokVideoObject();
                            videoObject.mVideoPaths = mUri;
                            TikTokMediaContent content = new TikTokMediaContent();
                            content.mMediaObject = videoObject;
                            request.mMediaContent = content;

// 调起分享
                            tiktokOpenApi.share(request);
                        }else {
                            Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
                        }




                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(file);
                        intent.setData(uri);
                        context.sendBroadcast(intent);

                        dismiss();

                    }

                    @Override
                    public void onDownloading(int progress) {

                        Log.e("file", progress + "");
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        Toast.makeText(context, "下载失败,请重试", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private String platFormName;
    private String price;
    private Platform platform;
    List<ShaixuanBean> list = new ArrayList<>();

    List<ShaixuanBean> list1 = new ArrayList<>();

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.view:
                this.dismiss();
                break;
            case R.id.tv_quxiao:
                this.dismiss();
                break;

        }
    }

    //抖音
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

    }

    @Override
    public void onCancel(Platform platform, int i) {

    }
    //抖音




    public interface SignListener {

        void jubao();

        void fuzhi();

    }

    private static final String SD_PATH = "/sdcard/dskqxt/pic/";
    private static final String IN_PATH = "/dskqxt/pic/";

    public String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()
                    + IN_PATH;
        }
        try {
            filePic = new File(savePath + generateFileName() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return filePic.getAbsolutePath();
    }


    /**
     * 随机生产文件名
     *
     * @return
     */
    private String generateFileName() {
        return UUID.randomUUID().toString();
    }

    private String logurl = "";

    Bitmap bitmap;

    public Bitmap getBitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

    private void toShare(String platFormName) {
        /**
         * title  标题
         * contenturl分享地址
         * logurl 项目log
         **/
        Resources res = context.getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, R.mipmap.test);
//        Bitmap bitmap = BitmapViewUtils.getBitmapByView(res, R.mipmap.icon_logo);//contentLly是布局文件
        if (logurl.equals("")) {
            logurl = saveBitmap(context, bmp);
//            lei = 1;
        }
        Log.e("======img",stringStringMap.get("img"));
        ShareForApp shareForApp = new ShareForApp(platFormName, stringStringMap.get("img"), stringStringMap.get("name"), stringStringMap.get("name"), stringStringMap.get("share"), (ShareBeBackListener) FenxiangDialog.this);
        /**
         * tyep 分享类型
         **/

        shareForApp.toShare();
        dismiss();
    }

    @Override
    public void beBack(ShareForApp.PlatformForShare platformForShare, ShareForApp.StatusForShare statusForShare, int code) {
        Log.e("statusForShare", statusForShare.toString());
    }

}

